package virtualstock.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import virtualstock.exception.InvalidParameterException;
import virtualstock.exception.PlayerNotFoundException;
import virtualstock.request.PlayerController;
import virtualstock.util.PlayerDetails;

/**
 * Servlet implementation class ListPlayerServlet
 */
public class ListPlayerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private PlayerController playerController; 
	
//	@PersistenceUnit
//	private EntityManagerFactory emf;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListPlayerServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
    	
//    	assert emf != null;
//    	EntityManager em = null;
    	
    	Long playerID = new Long(1);
    	try {
			PlayerDetails details = playerController.getPlayerDetails(playerID);
			
//    		em = emf.createEntityManager();
//    		List players = em.createQuery("select * from player p").getResultList();
			if (details != null) {
				request.setAttribute("details", details);
//				request.setAttribute("players", players);
			}
			else {
				out.print("Player not found");
			}
		} catch (InvalidParameterException e) {
			out.print("InvalidParameterException");
			e.printStackTrace();
		} catch (PlayerNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			out.print("Player not found");
		}
		
		request.getRequestDispatcher("ListPlayer.jsp").forward(request, response);
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
